import requests as r
import re
import json


def main(bv=""):
    # 修改视频的bv号，对不同视频的弹幕进行爬取
    # bv = https://www.bilibili.com/video/BV1ip4y1D7iY
    print(bv)
    url = "https://www.bilibili.com/video/" + bv
    b = r.get(url)
    av = re.findall('BV.*,"aid":(\d*)', b.text)[0]
    print(av)
    url = "https://api.bilibili.com/x/player/pagelist?aid=" + av
    cid = r.get(url).text
    # print(r.get(url).text)
    cid = json.loads(cid)['data'][0]['cid']
    print(cid)
    url = "https://api.bilibili.com/x/v1/dm/list.so?oid=" + str(cid)
    bc = r.get(url)
    bc.encoding = "utf-8"
    bc = bc.text
    a = re.compile('<([^>])+.')
    bc = a.sub('`', bc).split("`")
    while '' in bc:
        bc.remove('')
    bc = bc[7:]
    f = open("bc.json", "w", encoding="utf-8")
    f.write(json.dumps(bc))
    # print(bc)
    f.close()
    return bc


if __name__ == '__main__':
    main()
